﻿HmJS.$Import('core.element');

/*
---
name: DynamicMatcher
version: 1.0.5-0
description: Searches elements via complex selectors and executes functions on them. Very useful to define behavior for certain elements or when you control all content via XHR. Also might be of use if you have no control of the markup.
license: MIT-style license.
download: http://mootools.net/forge/p/dynamicmatcher
source: http://github.com/cpojer/mootools-dynamic-matcher/

authors: Christoph Pojer (@cpojer)

requires: [Core/Events, Core/Element]

provides: DynamicMatcher
...
*/

HmJS.register('util.dom.DynamicMatcher', function ($ns) {

	return new Class({

		Implements: Events,

		initialize: function () {
			this.expressions = [];
			this.handlers = [];
		},

		register: function (expression, fn) {
			var index = this.handlers.indexOf(fn);
			if (index != -1 && this.expressions[index] == expression) return this;

			this.expressions.push(expression);
			this.handlers.push(fn);

			return this;
		} .overloadSetter(),

		unregister: function (expression, fn) {
			var handlers = this.handlers,
			expressions = this.expressions;

			for (var i = 0, l = handlers.length; i < l; i++) if (expression == expressions[i] && fn == handlers[i]) {
				delete handlers[i];
				delete expressions[i];
				break;
			}

			return this;
		} .overloadSetter(),

		update: function (element) {
			element = document.id(element) || document;

			var isDocument = (element == document),
			handlers = this.handlers,
			expressions = this.expressions;

			for (var i = 0, l = handlers.length; i < l; i++) {
				var expression = expressions[i];
				if (!expression) continue;

				var elements = element.getElements(expression);
				if (!isDocument && element.match(expression)) elements.push(element);

				if (elements.length) handlers[i](elements);
			}

			this.fireEvent('update', [element]);

			return this;
		}

	});

});
